<template>
  <div class="user-wrap">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 搜索，添加用户 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="userInfo.query" class="input-with-select" clearable @clear="clearFn">
            <el-button slot="append" icon="el-icon-search" @click="searchFn"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4"><el-button type="primary" @click="addUserDialogVisible=true">添加用户</el-button></el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeStatusFn(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editFn(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteFn(scope.row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="settingFn(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="userInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!-- 添加用户 -->
      <el-dialog title="添加用户" :visible.sync="addUserDialogVisible" width="50%" @close="closeDialogUser">
        <span>
          <el-form :model="addRuleUserForm" :rules="addUserRules" ref="addRuleFormRef" label-width="70px" class="demo-ruleForm">
            <el-form-item label="姓名" prop="username">
              <el-input v-model="addRuleUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addRuleUserForm.password"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
              <el-input v-model="addRuleUserForm.mobile"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addRuleUserForm.email"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUserFn">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户信息 -->
      <el-dialog
        title="编辑用户信息"
        :visible.sync="dialogEditVisible"
        width="50%"
        @close="closeDialogEdit"
        >
        <span>
          <el-form :model="ruleEditForm" :rules="rulesEdit" ref="ruleEditFormRef" label-width="70px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="ruleEditForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="ruleEditForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="ruleEditForm.mobile"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogEditVisible = false">取 消</el-button>
          <el-button type="primary" @click="editTrueFn">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog title="分配角色" :visible.sync="dialogVisibleRoles" width="50%"  @close="closeDialogRole">
        <span>
          <p>姓名:  {{rolesInfo.username}}</p>
          <p>角色名称:  {{rolesInfo.role_name}}</p>
          <p>修改角色:
            <el-select v-model="rolesId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </p>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="rolesChangeFn">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Users',
  created () {
    this.getList()
  },
  data () {
    // 邮箱校验
    var validEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 手机号校验
    var validMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    return {
      userInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      addUserDialogVisible: false,
      // 添加用户信息
      addRuleUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 用户信息校验规则
      addUserRules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: validMobile, trigger: 'blur' }
        ]
      },
      dialogEditVisible: false,
      // 编辑的用户信息
      ruleEditForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 编辑的用户信息校验
      rulesEdit: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: validMobile, trigger: 'blur' }
        ]
      },
      dialogVisibleRoles: false,
      rolesInfo: {},
      rolesList: [],
      rolesId: ''
    }
  },
  methods: {
    // 获取表格数据
    async getList () {
      const { data: res } = await this.$http.get('users', { params: this.userInfo })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      console.log(this.userList)
      this.total = res.data.total
    },
    // 修改页容量
    handleSizeChange (size) {
      this.userInfo.pagesize = size
      this.getList()
    },
    // 修改页码
    handleCurrentChange (page) {
      this.userInfo.pagenum = page
      this.getList()
    },
    // 修改状态
    async changeStatusFn (row) {
      const { data: res } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('状态修改成功')
    },
    // 搜索
    searchFn () {
      this.getList()
    },
    clearFn () {
      this.getList()
    },
    // 关闭dialog，重置用户信息
    closeDialogUser () {
      this.$refs.addRuleFormRef.resetFields()
    },
    // 添加用户信息
    addUserFn () {
      // this.addUserDialogVisible = false
      this.$refs.addRuleFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入有效的信息')
        this.addUserDialogVisible = false
        const { data: res } = await this.$http.post('users', this.addRuleUserForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getList()
      })
    },
    // 根据id获取用户信息
    async editFn (id) {
      this.dialogEditVisible = true
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.message.error(res.meta.msg)
      this.ruleEditForm = res.data
    },
    // 修改用户信息
    editTrueFn () {
      this.$refs.ruleEditFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入有效的信息')
        this.dialogEditVisible = false
        const { data: res } = await this.$http.put(`users/${this.ruleEditForm.id}`, this.ruleEditForm)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getList()
      })
    },
    // 关闭dialog，重置用户信息
    closeDialogEdit () {
      this.$refs.ruleEditFormRef.resetFields()
    },
    // 删除
    deleteFn (id) {
      console.log(id)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`/users/${id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 获取角色列表
    async settingFn (row) {
      this.rolesInfo = row
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
      this.dialogVisibleRoles = true
    },
    // 设置角色
    async rolesChangeFn () {
      const { data: res } = await this.$http.put(`users/${this.rolesInfo.id}/role`, { rid: this.rolesId })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.dialogVisibleRoles = false
      this.getList()
    },
    closeDialogRole () {
      this.rolesId = ''
      this.rolesInfo = {}
    }
  }
}
</script>

<style>

</style>
